import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:lazy_food/components/keepAliveWrapper/keep_alive_arapper.dart';
import 'package:lazy_food/net/network.dart';
import 'package:lazy_food/util/string+.dart';
import '../../components/group/group.dart';
import '../../models/recipe_model.dart';
import '../../models/story_model.dart';
import '../../models/tab_model.dart';
import '../../models/vip_model.dart';

class RankPage extends StatefulWidget {
  TabModel tab;
  RankPage({Key? key, required this.tab}) : super(key: key);
  @override
  State<RankPage> createState() => _RankPageState();
}

class _RankPageState extends State<RankPage> {
  EasyRefreshController _refreshController =
      EasyRefreshController(controlFinishRefresh: true);
  List<VipModel> _models = [];

  void _onRefresh() {
    EasyLoading.show();
    Network.getHomeRank().then((value) {
      setState(() {
        _models = value;
      });
      _refreshController.finishRefresh();
      EasyLoading.dismiss();
    });
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.builder(
      controller: _refreshController,
      onRefresh: _onRefresh,
      refreshOnStart: true,
      childBuilder: (context, physics) {
        return KeepAliveWrapper(
          child: ListView.builder(
            physics: physics,
            itemCount: _models.length,
            itemBuilder: (context, index) {
              VipModel model = _models[index];
              List<RecipeModel>? recipes = model.data.recipes;
              List<StoryModel>? stories = model.data.stories;
              if (recipes != null) {
                return GroupView(
                  list: recipes.map(
                    (e) {
                      return GroupModel(e.image.url_pattern.toImage(), e.name);
                    },
                  ).toList(),
                  title: model.data.title,
                );
              } else if (stories != null) {
                return GroupView(
                  list: stories.map(
                    (e) {
                      return GroupModel(
                          e.cover_image.url_pattern.toImage(), e.name);
                    },
                  ).toList(),
                  title: model.data.title,
                );
              } else {
                return SizedBox(height: 0);
              }
            },
          ),
        );
      },
    );
  }
}
